<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Vue 3 父子交互</title>
  <script src="https://unpkg.com/vue@3"></script>
</head>
<body>
  <div id="app"></div>

  <script>
    // 定义子组件
    const ChildComponent = {
      props: ['message'], // 接收父组件的props
      template: `
        <div>
          <h2>子组件</h2>
          <p>子组件收到的消息: {{ message }}</p>
          <button @click="sendToParent">发送消息给父组件</button>
        </div>
      `,
      methods: {
        sendToParent() {
          // 触发子组件的事件并传递数据给父组件
          this.$emit('child-event', '来自子组件的消息');
        }
      }
    };

    // 定义父组件
    const ParentComponent = {
      components: { ChildComponent },
      template: `
        <div>
          <h2>父组件</h2>
          <p>父组件的数据: {{ parentMessage }}</p>
          <p>子组件的返回消息: {{ childMessage }}</p>
		  
          <child-component :message="parentMessage" @child-event="handleChildEvent"></child-component>
        </div>
      `,
      data() {
        return {
          parentMessage: '来自父组件的消息',
          childMessage: ''
        };
      },
      methods: {
        handleChildEvent(msg) {
          // 接收子组件的消息
          this.childMessage = msg;
          console.log('子组件发送的消息:', msg);
        }
      }
    };

    // 创建Vue应用实例
    const app = Vue.createApp({
      components: { ParentComponent },
      template: `<parent-component></parent-component>`
    });

    // 挂载到DOM
    app.mount('#app');
  </script>
</body>
</html>
